package ar.org.cfired.creditos.schedulers;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.jbpm.api.Configuration;
import org.jbpm.api.ExecutionService;
import org.jbpm.api.ProcessInstance;
import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

import ar.org.cfired.creditos.Solicitud;
import ar.org.cfired.hibernate.utils.HibernateUtil;

import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

public class InstanceCreator implements Job {
	 public void execute(JobExecutionContext arg0) throws JobExecutionException{
		    

			List<Solicitud> respuesta = null;
			Transaction tx = null;
			Session session = null;
			Session session2 = null;
			try {
				System.out.println("Scheduler de Creditos - Por iniciar sesion");
				session = HibernateUtil.getSessionFactory().getCurrentSession(); //.openSession();
				tx = session.beginTransaction();
				System.out.println("Scheduler de Creditos - Transaccion iniciada");
		    respuesta = (List<Solicitud>) session.createQuery("from Solicitud where cre_cargado_dprocess=0").list();
session.close();
		    System.out.println( "Scheduler de Roger -  " + respuesta.size() + " documento(s) nuevo(s)" );
		    /*if (respuesta.size() > 0) {
		    	session2 = HibernateUtil.getSessionFactory().getCurrentSession();
		    }*/
		    String textoFinal = "";
		    Map<String,Object> variables;
		    ProcessInstance processInstance;
		    ExecutionService executionService = new Configuration().buildProcessEngine().getExecutionService();
		    Solicitud loadedMsg = null;
		    for ( Iterator<Solicitud> iter = respuesta.iterator(); iter.hasNext(); ) {
		    	try {
		    		session2 = HibernateUtil.getSessionFactory().getCurrentSession();
		    	session2.beginTransaction();
		    	loadedMsg = (Solicitud) iter.next();
		        textoFinal += loadedMsg.getCreApoderadoEmail() +  " \n";
		      
		        variables = loadedMsg.getVariables(session2);
				processInstance = executionService.startProcessInstanceByKey("Creditos", variables);	            
		        
				loadedMsg.setCreCargadoDprocess(1);
				session2.update(loadedMsg);
		        session2.getTransaction().commit();
		    	}
		    	catch (HibernateException e) {
		    		System.out.println( "Scheduler de Creditos -  No se pudo cargar el documento - Hibernate Exception " + ((loadedMsg!=null)?loadedMsg.getCreId():""));
		    		System.out.println(e.getMessage());	
		    		if (session2.isOpen()) {
		    			session2.close();
		    			session2 = HibernateUtil.getSessionFactory().getCurrentSession();
		    		}
		    	}
		    	catch (Exception e) {
		    		System.out.println( "Scheduler de Creditos -  No se pudo cargar el documento - Exception " + ((loadedMsg!=null)?loadedMsg.getCreId():""));
		    		System.out.println(e.getMessage());
		    	}
		    	/*finally {
		    		if (session2 != null) {
		    			if (session2.isOpen()) {
		    				Transaction t2 = session2.getTransaction();
		    				if (t2 != null) {
		    					if (t2.isActive()) {
		    						t2.rollback();
		    					}
		    					t2 = null;
		    				}
		    				if (session2.isOpen())
		    					session2.close();
		    			}
		    			session2 = null;
		    		}
		    			
		    	}*/
		        //System.out.println( loadedMsg );
		    }
		    
		   // session.getTransaction().commit();
		    //session.close();
		    System.out.println(textoFinal);
			} 
			catch (HibernateException e){
				System.out.println("Scheduler de Creditos - " + e.getMessage());
				if (tx!=null) {
					if (!tx.wasRolledBack())
						tx.rollback();
					tx = null;
				}
			}
			catch (Exception e) {
				System.out.println("Scheduler de Creditos - " + e.getMessage());
			}
			finally {
				if (session!=null) {
					if (session.isOpen())
						session.close();
					session = null;
				}
				if (respuesta!=null) respuesta.clear();
			}
			
			System.out.println("Scheduler de Creditos - Terminado en " + new Date());
		 		 

		  }
}
